package com.lineage.server.model.Instance;

import com.add.L1PcUnlock;
import com.lineage.config.ConfigGuaji;
import com.lineage.server.clientpackets.AcceleratorChecker;
import com.lineage.server.datatables.SprTable;
import com.lineage.server.model.L1Object;
import com.lineage.server.model.L1Teleport;
import com.lineage.server.serverpackets.S_ServerMessage;
import com.lineage.server.serverpackets.ServerBasePacket;
import com.lineage.server.thread.NpcAiThreadPool;
import com.lineage.server.types.Point;
import com.lineage.server.world.World;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class PcAI implements Runnable {
  private static final Log _log = LogFactory.getLog(PcAI.class);
  
  private static Random _random = new Random();
  
  private final L1PcInstance _pc;
  
  public PcAI(L1PcInstance pc) {
    this._pc = pc;
  }
  
  public void startAI() {
    NpcAiThreadPool.get().execute(this);
  }
  
  public void run() {
    try {
      while (this._pc.getMaxHp() > 0 && 
        !AIProcess()) {
        try {
          Thread.sleep(getRightInterval(2));
        } catch (Exception e) {
          break;
        } 
      } 
      do {
        try {
          Thread.sleep((getRightInterval(1) + 15));
        } catch (Exception e) {
          break;
        } 
      } while (this._pc.isDead());
      this._pc.allTargetClear();
      this._pc.setAiRunning(false);
      this._pc.setActived(false);
      Thread.sleep(10L);
      return;
    } catch (Exception e) {
      _log.error("pcAI发生例外状况: " + this._pc.getName(), e);
      return;
    } 
  }
  
  private boolean AIProcess() {
    try {
      if (this._pc.isDead())
        return true; 
      if (this._pc.getOnlineStatus() == 0)
        return true; 
      if (this._pc.getCurrentHp() <= 0)
        return true; 
      if (!this._pc.isActived())
        return true; 
      if (ConfirmTheEnemy(this._pc))
        return true; 
      if (this._pc.getgo_guajired()) {
        Iterator<L1Object> iterator = World.get().getVisibleObjects((L1Object)this._pc, 8).iterator();
        while (iterator.hasNext()) {
          L1Object object = iterator.next();
          if (object instanceof L1PcInstance) {
            L1PcInstance red = (L1PcInstance)object;
            if (red.getLawful() >= 0 || red.isDead())
              continue; 
            L1Teleport.randomTeleport(this._pc, true);
            this._pc.sendPackets((ServerBasePacket)new S_ServerMessage("侦测到周围有红人玩家自动瞬移。"));
          } 
        } 
      } 
      if (this._pc.getInventory().getWeight240() >= 197) {
        this._pc.sendPackets((ServerBasePacket)new S_ServerMessage(110));
        this._pc.setActived(false);
        this._pc.sendPackets((ServerBasePacket)new S_ServerMessage("自动狩猎已停止。"));
        this._pc.set_fwgj(0);
        this._pc.setlslocx(0);
        this._pc.setlslocy(0);
        this._pc.killSkillEffectTimer(8853);
        L1Teleport.teleport(this._pc, 33440, 32802, (short)4, 0, true);
        L1PcUnlock.Pc_Unlock(this._pc);
        return true;
      } 
      if (this._pc.getWeapon() == null) {
        this._pc.sendPackets((ServerBasePacket)new S_ServerMessage("\\fU没拿武器，自动关闭挂机！"));
        this._pc.setActived(false);
        this._pc.sendPackets((ServerBasePacket)new S_ServerMessage("自动狩猎已停止。"));
        this._pc.set_fwgj(0);
        this._pc.setlslocx(0);
        this._pc.setlslocy(0);
        L1PcUnlock.Pc_Unlock(this._pc);
        this._pc.killSkillEffectTimer(8853);
        return true;
      } 
      Calendar date = Calendar.getInstance();
      int nowHour = date.get(11);
      if (ConfigGuaji.checktimeguaji) {
        int[] GUAJI_TIME = ConfigGuaji.GUAJI_ITEM;
        int array[], length = (array = GUAJI_TIME).length;
        int i = 0;
        while (i < length) {
          int guajitimme = array[i];
          if (nowHour == guajitimme) {
            this._pc.setActived(false);
            this._pc.sendPackets((ServerBasePacket)new S_ServerMessage("自动狩猎已停止。"));
            L1Teleport.teleport(this._pc, 33440, 32802, (short)4, 0, true);
            this._pc.set_fwgj(0);
            this._pc.setlslocx(0);
            this._pc.setlslocy(0);
            L1PcUnlock.Pc_Unlock(this._pc);
            this._pc.killSkillEffectTimer(8853);
            return true;
          } 
          i++;
        } 
      } 
      if (!this._pc.getMap().isGuaji() && this._pc.isActived()) {
        this._pc.setActived(false);
        this._pc.set_fwgj(0);
        this._pc.setlslocx(0);
        this._pc.setlslocy(0);
        this._pc.sendPackets((ServerBasePacket)new S_ServerMessage("此地图不能挂机"));
        this._pc.killSkillEffectTimer(8853);
        return true;
      } 
      if (this._pc.get_followmaster() == null && this._pc.getlslocx() > 0 && this._pc.getlslocy() > 0 && 
        this._pc.getLocation().getTileLineDistance(
          new Point(this._pc.getlslocx(), this._pc.getlslocy())) > this._pc.get_fwgj()) {
        L1Teleport.teleport(this._pc, this._pc.getlslocx(), this._pc.getlslocy(), this._pc.getMapId(), 0, true);
        if (this._pc.isPathfinding())
          this._pc.setrandomMoveDirection(_random.nextInt(7)); 
        this._pc.targetClear();
      } 
      int result = this._pc.speed_Attack().checkInterval(AcceleratorChecker.ACT_TYPE.MOVE);
      if (result == 2)
        _log.error("要求角色移动:速度异常(" + this._pc.getName() + ")"); 
      this._pc.checkTarget();
      boolean searchTarget = true;
      if (this._pc.is_now_target() != null)
        searchTarget = false; 
      if (searchTarget)
        this._pc.searchTarget(); 
      if (this._pc.is_now_target() == null) {
        if (!this._pc.isPathfinding())
          this._pc.setrandomMoveDirection(_random.nextInt(8)); 
        this._pc.noTarget();
        Thread.sleep(50L);
        return false;
      } 
      this._pc.onTarget();
      if (this._pc.isPathfinding())
        this._pc.setPathfinding(false); 
      Thread.sleep(50L);
    } catch (Exception e) {
      _log.error("pcAI发生例外状况: " + this._pc.getName(), e);
    } 
    return false;
  }
  
  private boolean ConfirmTheEnemy(L1PcInstance pc) {
    try {
      if (pc.IsEnemyTeleport()) {
        Iterator<L1Object> iterator = World.get().getVisibleObjects((L1Object)pc, 5).iterator();
        while (iterator.hasNext()) {
          L1Object objid = iterator.next();
          if (objid instanceof L1PcInstance) {
            L1PcInstance _pc1 = (L1PcInstance)objid;
            if (!pc.isInEnemyList(_pc1.getName()))
              continue; 
            L1Teleport.randomTeleport(pc, true);
          } 
        } 
      } 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    return false;
  }
  
  private int getRightInterval(int type) {
    int interval = 0;
    switch (type) {
      case 1:
        interval = SprTable.get().getAttackSpeed(this._pc.getTempCharGfx(), this._pc.getCurrentWeapon() + 1);
        return intervalR(type, interval);
      case 2:
        interval = SprTable.get().getMoveSpeed(this._pc.getTempCharGfx(), this._pc.getCurrentWeapon());
        return intervalR(type, interval);
    } 
    return 0;
  }
  
  private int intervalR(int type, int interval) {
    try {
      if (this._pc.isHaste())
        interval = (int)(interval * 0.755D); 
      if (type == 2 && this._pc.isFastMovable())
        interval = (int)(interval * 0.755D); 
      if (this._pc.isBrave())
        interval = (int)(interval * 0.755D); 
      if (this._pc.isElfBrave())
        interval = (int)(interval * 0.855D); 
      if (type == 1 && this._pc.isElfBrave())
        interval = (int)(interval * 0.9D); 
      if (this._pc.isBraveX())
        interval = (int)(interval * 0.755D); 
    } catch (Exception e) {
      _log.error(e.getLocalizedMessage(), e);
    } 
    return interval;
  }
}
